package org.flycloud.web.sso.client;

import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.flycloud.web.sso.common.Token;
import org.flycloud.web.util.UrlInfo;

public class MyAuthenticationFilter implements Filter {

	private String ssoServiceUrl;

	private Filter authenticationFilter;

	public MyAuthenticationFilter(String ssoServiceUrl, Filter authenticationFilter) {
		super();
		this.ssoServiceUrl = ssoServiceUrl;
		this.authenticationFilter = authenticationFilter;
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		authenticationFilter.init(filterConfig);
	}

	public String getLogoutPath(HttpServletRequest request) {
		String[] ss = request.getRequestURL().toString().split("\\/");
		String ctx = request.getContextPath();
		String ret = ss[0] + "//" + ss[2] + ctx + "/sso/co";
		System.out.println(ret);
		return ret;
	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {
		{
			HttpServletRequest request = (HttpServletRequest) servletRequest;
			HttpServletResponse response = (HttpServletResponse) servletResponse;
			String urlString = URLEncoder.encode(UrlInfo.parse(request).toString(), "UTF8");

			String context = request.getSession().getServletContext().getContextPath();
			Boolean login = (Boolean) request.getSession().getAttribute("login");
			if (login != null) {
				authenticationFilter.doFilter(request, response, filterChain);
				return;
			}

			String token = (String) request.getSession().getAttribute(Token.TOKEN);
			if (token == null) {
				token = request.getParameter(Token.TOKEN);
				if (token == null) {
					response.sendRedirect(ssoServiceUrl + "?url=" + urlString + "&logout="
							+ URLEncoder.encode(getLogoutPath(request), "UTF8"));
					return;
				}
			}
			request.getSession().setAttribute(Token.TOKEN, token);

			UrlInfo ui = UrlInfo.parse(request);
			ui.del(Token.TOKEN);

			response.sendRedirect(context + "/sso/ci?url=" + URLEncoder.encode(ui.toString(), "UTF8"));
		}
	}

	@Override
	public void destroy() {
		authenticationFilter.destroy();
	}
}